<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>鲜时蔬 - 购物车</title>
    <!-- 引入Vue.js -->
    <script src="../../js/vue.js"></script>
    <!-- 引入Element UI样式 -->
    <link  type="text/css" rel="stylesheet" href="../../css/index.css">
    <!-- 引入Element UI组件库 -->
    <script src="../../js/index.js"></script>
    <!-- 引入axios -->
    <script src="../../js/axios.min.js"></script>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: "Helvetica Neue", sans-serif; background-color: #f8fafb; }
        .container { width: 1140px; margin: 0 auto; padding: 0 15px; }
        @media (max-width: 1199px) { .container { width: 960px; } }
        @media (max-width: 991px) { .container { width: 720px; } }
        @media (max-width: 767px) { .container { width: 100%; } }

        .header { background: #fff; box-shadow: 0 2px 10px rgba(0,0,0,0.08); position: fixed; top: 0; left: 0; right: 0; z-index: 1000; }
        .header-content { display: flex; justify-content: space-between; align-items: center; padding: 15px 0; }
        .logo { display: flex; align-items: center; font-size: 22px; font-weight: bold; color: #27ae60; text-decoration: none; }
        .logo i { margin-right: 8px; }
        .nav { display: flex; }
        .nav a { margin: 0 15px; text-decoration: none; color: #555; font-size: 15px; padding: 5px 0; transition: all 0.3s; }
        .nav a:hover, .nav a.active { color: #27ae60; border-bottom: 2px solid #27ae60; }
        .user-actions { display: flex; align-items: center; }
        .user-actions button { margin-left: 15px; background: none; border: none; color: #666; cursor: pointer; font-size: 14px; display: flex; align-items: center; transition: all 0.3s; }
        .user-actions button:hover { color: #27ae60; }
        .user-actions button i { margin-right: 5px; }

        .main { padding-top: 90px; padding-bottom: 50px; }

        .cart-title { margin-bottom: 20px; font-size: 20px; font-weight: 600; }
        .cart-table { width: 100%; border-collapse: collapse; background: #fff; border-radius: 8px; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
        .cart-table th, .cart-table td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #f0f0f0; }
        .cart-table th { background-color: #f7f7f7; font-weight: 600; }
        .product-img { width: 60px; height: 60px; object-fit: cover; border-radius: 4px; }
        .quantity-btn { width: 28px; height: 28px; border: 1px solid #ddd; background: #fff; cursor: pointer; border-radius: 4px; }
        .quantity-input { width: 50px; height: 28px; text-align: center; border: 1px solid #ddd; margin: 0 5px; border-radius: 4px; }
        .total-price { color: #e53935; font-weight: bold; }
        .empty-cart { text-align: center; padding: 80px 0; background: #fff; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
        .empty-cart i { font-size: 50px; color: #ddd; margin-bottom: 15px; }
        .empty-cart p { color: #888; font-size: 16px; margin-bottom: 20px; }
        .footer { background: #2c3e50; color: #ecf0f1; padding: 40px 0; margin-top: 60px; }
        .footer-content { text-align: center; font-size: 14px; }
        .checkout-bar { display: flex; justify-content: space-between; align-items: center; margin-top: 20px; background: #fff; padding: 15px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); }
        .checkout-btn { background: #27ae60; color: #fff; border: none; padding: 8px 15px; border-radius: 4px; cursor: pointer; }
        .checkout-btn:hover { background: #2ecc71; }
        /* 用户信息下拉菜单 */
        .user-info { position: relative; display: flex; align-items: center; cursor: pointer; }
        .user-avatar { width: 32px; height: 32px; border-radius: 50%; background-color: #27ae60; color: white; display: flex; align-items: center; justify-content: center; margin-right: 8px; font-size: 14px; }
        .user-dropdown { position: absolute; top: 100%; right: 0; background: white; box-shadow: 0 2px 12px rgba(0,0,0,0.1); border-radius: 4px; padding: 5px 0; min-width: 120px; z-index: 10; margin-top: 5px; display: none; }
        .user-dropdown.show { display: block; }
        .user-dropdown-item { padding: 8px 15px; font-size: 14px; color: #606266; cursor: pointer; }
        .user-dropdown-item:hover { background-color: #f5f7fa; color: #27ae60; }
    </style>
</head>
<body>
<div id="app">
    <!-- 导航栏区域 -->
    <header class="header">
        <div class="container">
            <div class="header-content">
                <a href="index.html" class="logo">
                    <i class="el-icon-shopping-bag"></i>
                    <span>鲜时蔬</span>
                </a>
                <nav class="nav">
                    <a href="index.html">首页</a>
                    <a href="vegetables.html">蔬菜列表</a>
                    <a href="contact.html">联系我们</a>
                </nav>
                <div class="user-actions">
                    <!-- 根据登录状态显示不同内容 -->
                    <template v-if="isLoggedIn">
                        <div class="user-info" @mouseenter="showDropdown = true" @mouseleave="showDropdown = false">
                            <div class="user-avatar">
                                {{ loggedInUser.nickName ? loggedInUser.nickName.charAt(0) : loggedInUser.userName.charAt(0) }}
                            </div>
                            <span>{{ loggedInUser.nickName || loggedInUser.userName }}</span>
                            <div class="user-dropdown" :class="{ 'show': showDropdown }">
                                <div class="user-dropdown-item" @click="goToPersonalCenter">个人中心</div>
                                <div class="user-dropdown-item" @click="logout">退出登录</div>
                            </div>
                        </div>
                    </template>
                    <template v-else>
                        <button @click="goToLogin">
                            <i class="el-icon-user"></i> 登录
                        </button>
                    </template>
                </div>
            </div>
        </div>
    </header>

    <!-- 主内容区 -->
    <main class="main">
        <div class="container">
            <div class="cart-title">我的购物车</div>

            <!-- 购物车列表 -->
            <table class="cart-table" v-if="cartList.length > 0">
                <thead>
                <tr>
                    <th>商品图片</th>
                    <th>商品名字</th>
                    <th>商品所属店铺</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>小计</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="item in cartList" :key="item.cartId">
                    <td>
                        <img :src="item.imageUrl"
                             :alt="item.productName"
                             class="product-img">
                    </td>
                    <td>{{ item.productName }}</td>
                    <td>
                        <!-- 直接使用加入购物车时保存的shopName -->
                        {{ item.shopName ||  item.shopId || '未知店铺'}}
                    </td>
                    <td>¥{{ item.productPrice }}</td>
                    <td>
                        <button class="quantity-btn" @click="updateQuantity(item, -1)">-</button>
                        <input type="number" class="quantity-input" v-model="item.productCount" @change="updateQuantity(item, 0)">
                        <button class="quantity-btn" @click="updateQuantity(item, 1)">+</button>
                    </td>
                    <td class="total-price">¥{{ (item.productPrice * item.productCount).toFixed(2) }}</td>
                    <td>
                        <button class="el-button el-button--mini el-button--danger" @click="removeItem(item.cartId)">删除</button>
                    </td>
                </tr>
                </tbody>
            </table>

            <!-- 空购物车提示 -->
            <div class="empty-cart" v-else>
                <i class="el-icon-shopping-cart-1"></i>
                <p>您的购物车是空的</p>
                <el-button type="primary" @click="goToVegetables">去逛逛</el-button>
            </div>

            <!-- 结算栏 -->
            <div class="checkout-bar" v-if="cartList.length > 0">
                <div>
                    <button class="el-button el-button--warning" @click="clearCart">清空购物车</button>
                </div>
                <div>
                    <span>总价：</span>
                    <span class="total-price" style="font-size:18px;margin:0 10px;">¥{{ totalPrice.toFixed(2) }}</span>
                    <button class="checkout-btn" @click.prevent="goToCheckout">去结算</button>
                </div>
            </div>
        </div>
    </main>

    <!-- 页脚 -->
    <footer class="footer">
        <div class="container">
            <div class="footer-content">
                <p>© 2025 鲜时蔬 版权所有 | 京ICP备12345678号</p>
            </div>
        </div>
    </footer>
</div>

<script>
    new Vue({
        el: '#app',
        data() {
            return {
                isLoggedIn: false, // 登录状态标识
                loggedInUser: {},// 存储登录用户信息
                showDropdown: false, // 控制下拉菜单显示
                cartList: [], // 购物车列表数据
                cartCount: 0, // 购物车商品数量
                totalPrice: 0,// 购物车商品总价
            }
        },
        mounted() {
            // 页面挂载后，检查登录状态
            this.checkLoginStatus();
        },
        methods: {
            // 检查登录状态方法
            checkLoginStatus() {
                axios.get('/vegetablemarketexpress/user/checkLoginStatus', { withCredentials: true })
                    .then(res => {
                        if (res.data.code === 200 && res.data.data) {
                            this.isLoggedIn = true;
                            this.loggedInUser = res.data.data;
                            this.fetchCartList(); // 登录后获取购物车列表
                        } else {
                            this.isLoggedIn = false;
                            this.$message.warning('请先登录');
                            setTimeout(() => this.goToLogin(), 1000);
                        }
                    })
                    .catch(err => {
                        console.error('检查登录状态失败', err);
                        this.isLoggedIn = false;
                    });
            },
            // 获取购物车列表方法
            fetchCartList() {
                axios.get('/vegetablemarketexpress/shoppingCart/list', { withCredentials: true })
                    .then(res => {
                        if (res.data.code === 200) {
                            this.cartList = res.data.data || [];
                            this.cartCount = this.cartList.length;
                            this.calcTotalPrice();
                            this.fillProductDetails(); // 查看商品详情
                        }
                    })
                    .catch(err => {
                        console.error('获取购物车失败', err);
                        this.$message.error('获取购物车失败');
                    });
            },
            fillProductDetails() {
                // 遍历购物车列表时，同时获取索引index
                this.cartList.forEach((item, index) => {
                    axios.get(`/vegetablemarketexpress/product/selectProductById?productId=${item.productId}`)
                        .then(res => {
                            if (res.data.code === 200) {
                                const p = res.data.data;

                                // 关键：使用Vue.set添加响应式属性
                                // 参数1：要修改的数组（cartList）
                                // 参数2：数组索引（index）
                                // 参数3：属性名（如productName）
                                // 参数4：属性值（如p.productName）
                                //Vue 的响应式系统只会对初始化时就存在的属性进行监听。当你通过 Vue.set 添加属性时，会强制 Vue 对新属性进行响应式处理，这样数据更新后页面会立即刷新。
                                Vue.set(this.cartList[index], 'productName', p.productName);
                                Vue.set(this.cartList[index], 'imageUrl', p.imageUrl);

                                if (!p.shopName) {
                                    axios.post(`/vegetablemarketexpress/shopProduct/getShopNameByProductId?productId=${item.productId}`, {})
                                        .then(r => {
                                            if (r.data.code === 200) {
                                                Vue.set(this.cartList[index], 'shopName', r.data.data);
                                            } else {
                                                Vue.set(this.cartList[index], 'shopName', '未知店铺');
                                            }
                                        });
                                } else {
                                    Vue.set(this.cartList[index], 'shopName', p.shopName);
                                }
                            } else {
                                // 处理接口返回失败的情况
                                Vue.set(this.cartList[index], 'productName', '获取失败');
                                Vue.set(this.cartList[index], 'imageUrl', '');
                                Vue.set(this.cartList[index], 'shopName', '获取失败');
                            }
                        })
                        .catch(err => {
                            console.error('获取商品详情失败', err);
                            Vue.set(this.cartList[index], 'productName', '获取失败');
                            Vue.set(this.cartList[index], 'imageUrl', '');
                            Vue.set(this.cartList[index], 'shopName', '获取失败');
                        });
                });
            },
            // 计算购物车总价方法
            calcTotalPrice() {
                this.totalPrice = this.cartList.reduce((sum, item) => {
                    return sum + (item.productPrice * item.productCount);
                }, 0);
            },
            // 更新商品数量方法
            updateQuantity(item, change) {
                if (change === -1 && item.productCount <= 1) return;
                if (change !== 0) item.productCount += change;

                // 调用后端更新接口
                axios.post('/vegetablemarketexpress/shoppingCart/updateCount', {
                    cartId: item.cartId,
                    productCount: item.productCount
                }, { withCredentials: true })
                    .then(res => {
                        if (res.data.code !== 200) {
                            this.$message.error('更新失败');
                            this.fetchCartList(); // 回滚数据
                        } else {
                            this.calcTotalPrice();
                        }
                    });
            },
            // 删除购物车商品方法
            removeItem(cartId) {
                axios.post('/vegetablemarketexpress/shoppingCart/delete', { cartId }, { withCredentials: true })
                    .then(res => {
                        if (res.data.code === 200) {
                            this.$message.success('删除成功');
                            this.fetchCartList(); // 删除后重新获取购物车列表
                        } else {
                            this.$message.error('删除失败');
                        }
                    });
            },
            // 清空购物车方法
            clearCart() {
                this.$confirm('确定要清空购物车吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    axios.post('/vegetablemarketexpress/shoppingCart/clear', {}, { withCredentials: true })
                        .then(res => {
                            if (res.data.code === 200) {
                                this.$message.success('已清空');
                                this.cartList = [];
                                this.cartCount = 0;
                                this.totalPrice = 0;
                            }
                        });
                });
            },
            // 跳转到结算页面
            goToCheckout() {
                if (this.cartList.length === 0) {
                    this.$message.warning('购物车为空，无法结算');
                    return;
                }
                // 将购物车数据转为 JSON 字符串，通过 URL 参数传递
                const cartData = encodeURIComponent(JSON.stringify(this.cartList));
                const userId = this.loggedInUser.userId;
                window.location.href = `createOrder.html?cartData=${cartData}&userId=${userId}`;
            },
            // 跳转方法
            goToLogin() { window.location.href = 'login.html'; },
            goToVegetables() { window.location.href = 'vegetables.html'; },
            // 跳转到个人中心
            goToPersonalCenter() {
                this.$message.info('即将跳转到个人中心');
                window.location.href = '/vegetablemarketexpress/html/front/personalCenter.html';
            },
            // 退出登录方法
            logout() {
                axios.get('/vegetablemarketexpress/user/logout', { withCredentials: true })
                    .then(() => {
                        this.isLoggedIn = false;
                        this.showDropdown = false;
                        this.$message.success('已退出登录');
                        setTimeout(() => this.goToLogin(), 1000);
                    });
            }
        }
    });
</script>
</body>
</html>
